// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// T [author] rhyme_lph
// P [email]  rhymelph@gmail.com
// C [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/format/service_and_product_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/page/dashboard/products_services/quantity_page.dart';
import 'package:finance_app/src/widgets/bottom_sheet/list_select_bottom_sheet.dart';
import 'package:flutter/material.dart';

class QuantityProvider extends BaseProvider {
  TextEditingController nameController = TextEditingController();
  FocusNode nameFocusNode = FocusNode();
  TextEditingController unitPriceController = TextEditingController();
  FocusNode unitPriceFocusNode = FocusNode();
  TextEditingController discountController = TextEditingController();
  FocusNode discountFocusNode = FocusNode();
  bool gstInclusive;

  bool enabledDiscount = false;
  bool isCheckPercentage = false;

  SettingDataTax gstRate;

  int number;

  bool isFromEdit = false;

  ProductEntity product;
  ServicesEntity services;
  bool isPurchaseRelated;

  @override
  Future get dataFuture => null;

  void initData(ProductEntity product, ServicesEntity service, int number,
      bool usePurchasePrice) {
    isFromEdit = number != null;
    isPurchaseRelated = usePurchasePrice;

    // if form edit, always use selling price
    bool isPurchasePrice = !isFromEdit && usePurchasePrice;

    this.product = product;
    this.services = service;
    if (number != null) {
      this.number = number;
    }
    if (product != null && product.id != null) {
      nameController.text = product.name;

      if (product.discountValue != null && product.discountValue != 0) {
        enabledDiscount = true;
        discountController.text = product.discountValue.toString();
        isCheckPercentage = product.discountType == 'percentage';
      }

      unitPriceController.text = isPurchasePrice
          ? product.purchasePrice.toString()
          : product.price.toString();
      gstInclusive = isPurchasePrice
          ? product.purchaseIsTaxInclusive == 1
          : product.isTaxInclusive == 1;
      gstRate = isPurchasePrice ? product.purchaseTax : product.tax;
    } else if (service != null && service.id != null) {
      nameController.text = service.name;

      if (service.discountValue != null && service.discountValue != 0) {
        enabledDiscount = true;
        discountController.text = service.discountValue.toString();
        isCheckPercentage = service.discountType == 'percentage';
      }

      unitPriceController.text = isPurchasePrice
          ? service.purchasePrice.toString()
          : service.price.toString();
      gstInclusive = isPurchasePrice
          ? service.purchaseIsTaxInclusive == 1
          : service.isTaxInclusive == 1;
      gstRate = isPurchasePrice ? service.purchaseTax : service.tax;
    }

    if (unitPriceController.text == '0') {
      unitPriceController.clear();
    }
  }

  void onSelectNumber(int value) {
    number = value;
  }

  @override
  void dispose() {
    super.dispose();
    nameController.dispose();
    nameFocusNode.dispose();
    unitPriceController.dispose();
    unitPriceFocusNode.dispose();
    discountController.dispose();
    discountFocusNode.dispose();
  }

  void onAddItem() {
    print(number);

    if (unitPriceController.text == null) {
      showToast(S.current.please_enter_the_unit_price);
      return;
    }
    if (number == null || number == 0) {
      showToast(S.current.please_enter_the_quantity);
      return;
    }

    if (product != null &&
        product.hasInventory == 1 &&
        number != null &&
        number > product.inventoryLeft &&
        !isPurchaseRelated) {
      showToast(S.current
          .no_enough_quantity_maximum_quantity_is_(product.inventoryLeft));
      return;
    }

    if (enabledDiscount) {
      if (discountController.text == null || discountController.text == '') {
        showToast(S.current.please_enter_the_discount);
        return;
      }
      if (isCheckPercentage == false) {
        num discountAmount = num.parse(discountController.text);
        num unitPrice = num.parse(unitPriceController.text);
        if (discountAmount > unitPrice * number) {
          showToast(
              S.current.discount_amount_cannot_be_greater_than_total_price);
          return;
        }
      }
    }

    if (services != null) {
      services.name = nameController.text;
      services.price =
          num.parse(unitPriceController.text ?? '0.0', (e) => null);
      services.isTaxInclusive = gstInclusive == true ? 1 : 0;
      services.tax =
          Config.currentCompany.enableGst == 1 ? gstRate : Config.noneTax;

      if (enabledDiscount) {
        services.discountValue = num.parse(discountController.text ?? '0.0');
        services.discountType = isCheckPercentage ? 'percentage' : 'value';
      } else {
        services.discountValue = 0;
        services.discountType = null;
      }
    }
    if (product != null) {
      product.name = nameController.text;
      product.price = num.parse(unitPriceController.text ?? '0.0', (e) => null);
      product.isTaxInclusive = gstInclusive == true ? 1 : 0;
      product.tax =
          Config.currentCompany.enableGst == 1 ? gstRate : Config.noneTax;

      if (enabledDiscount) {
        product.discountValue = num.parse(discountController.text ?? '0.0');
        product.discountType = isCheckPercentage ? 'percentage' : 'value';
      } else {
        product.discountValue = 0;
        product.discountType = null;
      }
    }

    if (isFromEdit) {
      obtainContext?.call((context) {
        Navigator.of(context)
          ..pop({
            'data': ServiceAndProductEntity()
              ..services = services
              ..product = product
              ..number = number,
          });
      });
    } else {
      obtainContext?.call((context) {
        Navigator.of(context)
          ..pop()
          ..pop({
            'data': ServiceAndProductEntity()
              ..services = services
              ..product = product
              ..number = number,
          });
      });
    }
  }

  void unFocus() {
    nameFocusNode.unfocus();
    unitPriceFocusNode.unfocus();
    discountFocusNode.unfocus();
  }

  void onDelete() {
    obtainContext?.call((context) {
      Navigator.of(context)
        ..pop({
          'delete': true,
        });
    });
  }

  void onChangeDiscount() {
    enabledDiscount = !enabledDiscount;
    if (enabledDiscount == false) {
      isCheckPercentage = false;
      discountController.clear();
    }
    update();
  }

  void onChangeGstInclusive() {
    unFocus();
    obtainContext?.call((context) async {
      final result = await showGstInclusiveBottomSheet(context, gstInclusive);
      if (result != null) {
        gstInclusive = result;
        update();
      }
    });
  }

  void onChangeIsPercentage(bool isPercentage) {
    isCheckPercentage = isPercentage;
  }

  void onChangeGstRate() {
    unFocus();
    obtainContext?.call((context) async {
      final result = await showGstRateBottomSheet(context, gstRate);
      if (result != null) {
        gstRate = result;
        update();
      }
    });
  }
}
